package controllers

import (
	"books/models"
	"encoding/json"
	beego "github.com/beego/beego/v2/server/web"
	"path/filepath"
	"strconv"
	"strings"
	"time"
)

type BooksController struct {
	beego.Controller
}

func (c *BooksController) Add() {
	title := c.GetString("title")
	author := c.GetString("author")
	img := c.GetString("img")
	status := c.GetString("status")
	cateId, _ := c.GetInt("cateId")

	books := models.Books{
		Title:  title,
		Author: author,
		Img:    img,
		Status: status,
		CateId: uint(cateId),
	}

	err := models.DB.Create(&books).Error
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 0,
			Msg:  "添加失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	} else {
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "添加成功",
			Data: nil,
		}
		c.ServeJSON()
	}
}

func (c *BooksController) Upload() {
	file, header, err := c.GetFile("img")
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 0,
			Msg:  "文件获取失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	}

	if header.Size > 2*1024*1024 {
		c.Data["json"] = JsonR{
			Code: 0,
			Msg:  "文件过大",
			Data: nil,
		}
		c.ServeJSON()
		return
	}

	defer file.Close()
	path := "static/img/" + header.Filename

	exit := map[string]bool{
		".png":  true,
		".jpeg": true,
		".jpg":  true,
	}
	suffix := strings.ToLower(filepath.Ext(header.Filename))
	if !exit[suffix] {
		c.Data["json"] = JsonR{
			Code: 0,
			Msg:  "仅支持PNG、JPEG、JPG格式",
			Data: nil,
		}
		c.ServeJSON()
		return
	}

	err = c.SaveToFile("img", path)
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 0,
			Msg:  "上传失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	} else {
		Img := "http://127.0.0.1:8080/" + path
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "上传成功",
			Data: Img,
		}
		c.ServeJSON()
	}
}

func (c *BooksController) List() {
	page, _ := c.GetInt("page", 1)
	size, _ := c.GetInt("size", 5)
	title := c.GetString("title")

	key := "list:" + strconv.Itoa(page) + title
	val, err := models.Rdb.Get(key).Result()

	jsonData := make(map[string]interface{})
	query := models.DB.Model(&models.Books{})

	if title != "" {
		query.Where("title like ?", "%"+title+"%")
	}

	if err != nil {
		var count int64
		query.Count(&count)
		offset := (page - 1) * size
		var books []models.Books
		err = models.DB.Preload("BookType").Offset(offset).Limit(size).Find(&books).Error
		if err != nil {
			c.Data["json"] = JsonR{
				Code: 0,
				Msg:  "查询失败",
				Data: nil,
			}
			c.ServeJSON()
			return
		} else {

			jsonData["count"] = count
			jsonData["books"] = books

			res, _ := json.Marshal(&jsonData)
			value := string(res)
			models.Rdb.Set(key, value, time.Second*60)

			c.Data["json"] = JsonR{
				Code: 200,
				Msg:  "查询成功-mysql",
				Data: jsonData,
			}
			c.ServeJSON()
		}
	} else {
		json.Unmarshal([]byte(val), &jsonData)
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "查询成功-redis",
			Data: jsonData,
		}
		c.ServeJSON()
	}

}

func (c *BooksController) Del() {
	id, _ := c.GetInt("id")
	var book models.Books
	err := models.DB.Where("id=?", id).First(&book).Error
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 0,
			Msg:  "查询失败",
			Data: nil,
		}
	}
	if book.Status != "已发布" {
		err = models.DB.Delete(&models.Books{}, id).Error
		if err != nil {
			c.Data["json"] = JsonR{
				Code: 0,
				Msg:  "删除失败",
				Data: nil,
			}
			c.ServeJSON()
		} else {
			c.Data["json"] = JsonR{
				Code: 200,
				Msg:  "删除成功",
				Data: nil,
			}
			c.ServeJSON()
			return
		}
	} else {
		c.Data["json"] = JsonR{
			Code: 0,
			Msg:  "删除失败,状态为已发布，禁止删除",
			Data: nil,
		}
		c.ServeJSON()
		return
	}

}

func (c *BooksController) Info() {
	id, _ := c.GetInt("id")
	var books models.Books

	key := "info:" + strconv.Itoa(id)
	val, err := models.Rdb.Get(key).Result()

	if err != nil {
		err = models.DB.Preload("BookType").Where("id=?", id).First(&books).Error
		if err != nil {
			c.Data["json"] = JsonR{
				Code: 0,
				Msg:  "查询失败",
				Data: nil,
			}
			c.ServeJSON()
			return
		} else {

			res, _ := json.Marshal(&books)
			value := string(res)
			models.Rdb.Set(key, value, time.Second*60)

			c.Data["json"] = JsonR{
				Code: 200,
				Msg:  "查询成功-mysql",
				Data: books,
			}
			c.ServeJSON()
			return
		}
	} else {
		json.Unmarshal([]byte(val), &books)
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "查询成功-redis",
			Data: books,
		}
		c.ServeJSON()
	}

}

func (c *BooksController) Collect() {
	bookId, _ := c.GetInt("bookId")
	userId, _ := c.GetInt("userId")

	collect := models.Collect{
		BookId: uint(bookId),
		UserId: uint(userId),
	}

	err := models.DB.Preload("Books").Preload("User").Create(&collect).Error
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 0,
			Msg:  "不登录无法收藏",
			Data: nil,
		}
		c.ServeJSON()
		return
	} else {
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "收藏成功",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
}

func (c *BooksController) CollList() {
	var coll []models.Collect
	err := models.DB.Preload("Books").Preload("User").Find(&coll).Error
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 0,
			Msg:  "收藏查看失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	} else {
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "收藏查看成功",
			Data: coll,
		}
		c.ServeJSON()
		return
	}
}

func (c *BooksController) Commit() {
	author := c.GetString("author")
	bookId, _ := c.GetInt("bookId")
	userId, _ := c.GetInt("userId")

	commit := models.Commit{
		Author: author,
		BookId: uint(bookId),
		UserId: uint(userId),
	}
	err := models.DB.Create(&commit).Error
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "评论成功",
			Data: nil,
		}
		c.ServeJSON()
		return
	} else {
		c.Data["json"] = JsonR{
			Code: 0,
			Msg:  "评论失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
}
